package cn.bluethink.eguan.trader.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.bluethink.eguan.core.service.EgAcountService;
import cn.bluethink.eguan.core.service.EgBagService;
import cn.bluethink.eguan.core.service.EgBtsService;
import cn.bluethink.eguan.core.service.EgGoodsHistoryService;
import cn.bluethink.eguan.core.service.EgGoodsService;
import cn.bluethink.eguan.model.core.EgBag;
import cn.bluethink.eguan.model.core.EgConfigInfo;
import cn.bluethink.eguan.model.core.EgGoods;
import cn.bluethink.eguan.model.core.EgOType;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.model.trader.EgTrader;
import cn.bluethink.eguan.model.trader.EgTraderStatus;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.trader.entity.EgTraderEntity;
import cn.bluethink.eguan.trader.entity.TraderEntity;
import cn.bluethink.eguan.trader.filter.TraderFilter;
import cn.bluethink.eguan.trader.mapper.EgTraderMapper;
import cn.bluethink.eguan.utils.DateUtil;
import cn.bluethink.eguan.utils.IdMakerUtils;
import tk.mybatis.mapper.entity.Example;

/**
 * 神秘商人业务层
 * 
 * @author 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.3.0
 * @brief 驿馆+产品
 * @note 修订历史： 1.wanglei于2018/11/26设计并构建初始版本v0.3.0
 */
@Service
public class EgTraderService {

    @Autowired
    private EgTraderMapper traderMapper;

    @Autowired
    private EgAcountService acountService;

    @Autowired
    private EgBagService bagService;

    @Autowired
    private EgConfigInfo configInfo;

    @Autowired
    private EgGoodsService goodsService;

    @Autowired
    private EgGoodsHistoryService goodsHistoryService;

    @Autowired
    private EgBtsService btsService;

    private IdMakerUtils idMakerUtil = new IdMakerUtils();

    /**
     * 创建神秘商人
     * 
     * @param trader
     * @param acountId
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgTrader create(EgTrader trader, Long acountId) throws Exception {
        // 创建神秘包裹
        EgBag exbag = bagService.create("神秘包裹");
        if (exbag == null) {
            throw new RuntimeException("创建失败，请重试！");
        }
        trader.setExbag(exbag);
        trader.setId(idMakerUtil.nextId());
        // 设置实际截止时间为截止日期当天晚上12点
        if (trader.getEtime() != null) {
            trader.setEtime(DateUtil.dateTime(trader.getEtime(), 23, 59, 59));
        }
        EgTraderEntity entity = new EgTraderEntity(trader, acountId);
        int insertCount = traderMapper.insertSelective(entity);
        return insertCount > 0 ? entity.createEgTrader() : null;
    }

    /**
     * 删除神秘商人(逻辑删除)
     * 
     * @param id
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean del(Long id) throws Exception {
        EgTraderEntity entity = new EgTraderEntity();
        entity.setId(id);
        entity.setDeleteFlag(true);
        int upCount = traderMapper.updateByPrimaryKeySelective(entity);
        return upCount > 0 ? true : false;
    }

    /**
     * 更新神秘商人信息(时间戳控制)
     * 
     * @param trader
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgTrader update(EgTrader trader) throws Exception {
        EgTraderEntity entity = new EgTraderEntity(trader);
        Example example = new Example(EgTraderEntity.class);
        example.and().andEqualTo("id", trader.getId()).andEqualTo("deleteFlag", false).andEqualTo("utime",
                trader.getUtime());
        int upCount = traderMapper.updateByExampleSelective(entity, example);
        trader.setUtime(entity.getUtime());
        return upCount > 0 ? trader : null;
    }

    /**
     * 查询神秘商人详情(未被删除的)
     * 
     * @param id
     * @return
     * @throws Exception
     */
    public EgTrader detail(Long id) throws Exception {
        // 查询条件
        String whereSql = " id = " + id + " AND delete_flag = 0 ";
        List<TraderEntity> entities = traderMapper.selectTradersByCondition(whereSql);
        if (entities != null && entities.size() > 0) {
            // 只查询一条记录
            return entities.get(0).createEgTrader();
        }
        return null;
    }

    /**
     * 转移操作：未兑换的商品转到历史商品记录中
     * 
     * @param trader
     * @param bDelelt
     *            表示是否是逻辑删除商人
     * @param bUpdate
     *            表示是否更新商人状态
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean transfer(EgTrader trader, Boolean bDelelt, Boolean bUpdate) throws Exception {
        // 逻辑删除神秘商人
        if (bDelelt) {
            if (!del(trader.getId())) {
                throw new RuntimeException("操作失败，请重试！");
            }
        }
        // 更新神秘商人状态为已结束
        if (bUpdate) {
            trader.setStatus(EgTraderStatus.STATUS_FINISH);
            if (update(trader) == null) {
                throw new RuntimeException("操作失败，请重试！");
            }
        }
        EgBag bag = trader.getExbag();
        if (bag == null || bag.getId() == null || bag.getId() == 0) {
            return false;
        }
        // 获取包裹里的所有未兑换的商品列表(为空直接返回true)
        List<EgGoods> goodsList = goodsService.getGoodsList(bag.getId());
        if (goodsList != null && goodsList.size() > 0) {
            // 将未兑换商品转移到历史记录中
            if (!goodsHistoryService.createList(goodsList)) {
                throw new RuntimeException("转为历史商品时操作失败，请重试！");
            }
            return true;
        }
        return true;
    }

    /**
     * 根据包裹ID查询神秘商人的基本信息
     * 
     * @param bagId
     * @return
     * @throws Exception
     */
    public EgTrader getTraderByBagId(Long bagId) throws Exception {
        Example example = new Example(EgTraderEntity.class);
        example.and().andEqualTo("bagid", bagId).andEqualTo("deleteFlag", false);
        EgTraderEntity entity = traderMapper.selectOneByExample(example);
        if (entity == null) {
            return null;
        }
        EgTrader trader = entity.createEgTrader();
        return (trader != null) ? trader : null;
    }

    /**
     * 根据委托者和商人隶属的门派/江湖，查询该委托者正在扮演的商人。
     * 要求：未删除、未结束、未截止
     * 
     * @param actorId
     * @param fid
     * @return
     * @throws Exception
     */
    public EgTrader getTraderByActorAndFid(Long actorId, Long fid) throws Exception {
        Example example = new Example(EgTraderEntity.class);
        example.and().andEqualTo("actor", actorId).andEqualTo("deleteFlag", false)
                .andBetween("status", EgTraderStatus.STATUS_NEW, EgTraderStatus.STATUS_HANDLE)
                .andGreaterThan("etime", new Date()).andEqualTo("fid", fid);
        EgTraderEntity entity = traderMapper.selectOneByExample(example);
        if (entity == null) {
            return null;
        }
        EgTrader trader = entity.createEgTrader();
        return (trader != null) ? trader : null;
    }

    /**
     * 根据包裹ID获取神秘商人的ID以及引用的账户ID
     * 
     * @param bagId
     * @return
     * @throws Exception
     */
    public Map<String, Long> getTraderMapByBagId(Long bagId) throws Exception {
        Example example = new Example(EgTraderEntity.class);
        example.and().andEqualTo("bagid", bagId).andEqualTo("deleteFlag", false);
        EgTraderEntity entity = traderMapper.selectOneByExample(example);
        if (entity == null) {
            return null;
        }
        Map<String, Long> traderMap = new HashMap<>();
        traderMap.put("traderId", entity.getId());
        traderMap.put("acountId", entity.getAcount());
        return traderMap;
    }

    /**
     * 添加商品
     * 
     * @param trader
     * @param goods
     * @param uid
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods createGoods(EgTrader trader, EgGoods goods, Long uid) throws Exception {
        // 获取商品的总价
        Integer totalBt = goods.getPrice() * goods.getNumber();
        if (goodsService.create(goods, uid) == null) {
            throw new RuntimeException("创建商品失败！");
        }
        // 更新神秘商人拥有商品的总价信息
        trader.setTotalBt(trader.getTotalBt() + totalBt);
        if (update(trader) == null) {
            throw new RuntimeException("创建商品失败！");
        }
        return goods;
    }

    /**
     * 删除商品
     * 
     * @param trader
     * @param goods
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean delGoods(EgTrader trader, EgGoods goods) throws Exception {
        // 获取被兑换的商品总价
        Integer totalExBt = goods.getPrice() * goods.getNumber();
        if (goodsService.del(goods.getId()) == null) {
            throw new RuntimeException("删除商品失败！");
        }
        // 更新神秘商人拥有商品的总价信息
        trader.setTotalBt(trader.getTotalBt() - totalExBt);
        if (update(trader) == null) {
            throw new RuntimeException("删除商品失败！");
        }
        return true;
    }

    /**
     * 更新商品
     * 
     * @param trader
     * @param oldGoods
     * @param goods
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods updateGoods(EgTrader trader, EgGoods oldGoods, EgGoods goods) throws Exception {
        // 更新前获取该商品的价格
        Integer oldTotalBt = oldGoods.getPrice() * oldGoods.getNumber();
        // 更新操作
        EgGoods newGoods = goodsService.update(oldGoods, goods);
        if (newGoods == null) {
            throw new RuntimeException("编辑商品失败！");
        }
        // 获取编辑后的商品总价
        Integer newTotalBt = newGoods.getPrice() * newGoods.getNumber();
        // 更新神秘商人拥有商品的总价信息
        trader.setTotalBt(trader.getTotalBt() - oldTotalBt + newTotalBt);
        if (update(trader) == null) {
            throw new RuntimeException("编辑商品失败！");
        }
        return newGoods;
    }

    /**
     * 兑换商品
     * 
     * @param oldGoods
     * @param goods
     * @param acount
     * @param user
     * @param traderId
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods exchange(EgGoods oldGoods, EgGoods goods, Long acount, EgUser user, Long traderId) throws Exception {
        // 获取被兑换商品的价格
        Integer price = oldGoods.getPrice();
        // 获取待兑换的商品的数量(默认为1)
        Integer number = goods.getNumber() == null ? 1 : goods.getNumber();
        // 兑换所花的金币
        Integer exBt = price * number;
        // 被兑换的商品数量减1
        if (oldGoods.getRemain() - number < 0) {
            throw new RuntimeException("被兑换的商品数量不足！");
        }
        oldGoods.setRemain(oldGoods.getRemain() - number);
        if (goodsService.update(oldGoods, null) == null) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        // 神秘商人引用的账户增加金币
        if (!acountService.updateAcount(acount, exBt, true)) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        // 兑换的商品保存到商品历史表中（表中历史商品数量增加number），且历史表中的商品所有者为兑换的当前用户
        oldGoods.setNumber(number);
        oldGoods.setOwner(user);
        EgGoods goodsHistory = goodsHistoryService.create(oldGoods);
        if (goodsHistory == null) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        // 兑换者的账户扣除相应金币
        if (!acountService.updateAcount(user.getAcount().getId(), exBt, false)) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        // 神秘商人的兑换金币总额增加
        EgTrader trader = detail(traderId);
        if (trader == null) {
            return null;
        }
        trader.setExbt(trader.getExbt() + exBt);
        if (update(trader) == null) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        // 记录金币流通记录
        if (btsService.create(user.getAcount().getId(), oldGoods, price, number, acount) == null) {
            throw new RuntimeException("兑换商品失败，请重试！");
        }
        return goodsHistory;
    }

    /**
     * 注意：当神秘商人结束时，把剩余商品转移到历史商品中 ，另外将商人状态改为已结束。 定时任务执行时间：每天凌晨00：01:00
     * 
     * @throws Exception
     */
    @Scheduled(cron = "0 1 0 * * ?")
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public void TimedTask() throws Exception {
        // 查询过期的神秘商人列表
        Example example = new Example(EgTraderEntity.class);
        example.and().andEqualTo("deleteFlag", false).andLessThan("etime", new Date());
        List<EgTraderEntity> entities = traderMapper.selectByExample(example);
        if (entities != null && entities.size() > 0) {
            for (EgTraderEntity entity : entities) {
                EgTrader trader = entity.createEgTrader();
                // 只将状态是进行中的商人状态改为已结束
                if (trader.getStatus().equals(EgTraderStatus.STATUS_HANDLE)) {
                    if (!transfer(trader, false, true)) {
                        throw new RuntimeException("操作失败，请重试！");
                    }
                }
            }
        }
    }

    /**
     * 过滤查询神秘商人
     * 
     * @param filter
     * @param user
     * @return
     * @throws Exception
     */
    public PageInfo<EgTrader> query(TraderFilter filter, EgUser user) throws Exception {
        Integer pageNum = filter.getPageNum() == null ? 1 : filter.getPageNum();
        Integer pageSize = filter.getPageSize() == null ? 50 : filter.getPageSize();
        // 构造查询条件
        String whereSql = buildQuerySql(filter, user);
        // 返回结果
        List<EgTrader> result = new ArrayList<>();
        List<TraderEntity> entities = new ArrayList<>();
        // 判断whereSql不为空，根据条件查询
        if (StringUtils.isNotBlank(whereSql)) {
            // 分页
            PageHelper.startPage(pageNum, pageSize);
            entities = traderMapper.selectTradersByCondition(whereSql);
        }
        PageInfo<TraderEntity> oldPageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0) {
            for (TraderEntity entity : entities) {
                EgTrader trder = entity.createEgTrader();
                result.add(trder);
            }
        }
        return new PageInfo<>(result, oldPageInfo);
    }

    /**
     * 构建query查询条件
     * 
     * @param filter
     * @param user
     * @return
     * @throws Exception
     */
    private String buildQuerySql(TraderFilter filter, EgUser user) throws Exception {
        String whereSql = "";
        List<String> whereSqlList = new ArrayList<>();
        // 获取对象类型ID
        Long id = filter.getId() == null ? 0 : filter.getId();
        Boolean buid = filter.getBuid() == null ? false : filter.getBuid();
        // 获取用户位置对象类型ID，以及用户位置对象ID
        Integer otype = user.getPos().getType().getOtid();
        Long oid = user.getPos().getId();
        // 查看商人记录
        Boolean traderHistory = filter.getTraderHistory();

        whereSqlList.add(" 1 = 1 ");
        // 如果用户在门派中，查询在门派中创建的神秘商人
        if (otype.equals(EgOType.FACTION)) {
            whereSqlList.add(" T.acount = (SELECT acount FROM eg_faction WHERE fid = " + oid + ")");
        }
        // 如果用户在江湖中，查询在江湖中创建的神秘商人
        if (otype.equals(EgOType.JIANGHU)) {
            whereSqlList.add(" T.acount = " + configInfo.getAcountId());
        }
        // 所有查询的商人，都是未删除的
        whereSqlList.add(" T.delete_flag = 0 ");
        // 如果查看商人记录，展示已经结束的商人列表，按照创建时间的顺序进行排序，早创建的在前面
        if (traderHistory != null && traderHistory) {
            whereSqlList.add(" T.status = " + EgTraderStatus.STATUS_FINISH);
        } else {
            // 默认查看商人列表，展示未开始的或者进行中的
            whereSqlList.add(" T.status != " + EgTraderStatus.STATUS_FINISH);
        }
        // 根据创建者的ID过滤查询
        if (id > 0 && buid) {
            whereSqlList.add(" T.uid = " + id);
        }
        // 设置查询条件AND连接符
        if (whereSqlList.size() > 0) {
            whereSql += String.join(" AND ", whereSqlList);
        }
        // 按照创建时间正序排序
        whereSql += " ORDER BY T.ctime ";
        return whereSql;
    }
}
